﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Esint.Common.Security
{
    public class SecurityHelper
    {
        //构造函数
        public SecurityHelper()
        {

        }

        /// <summary>
        /// 加密指定字符串
        /// </summary>
        /// <param name="strClearText">明文</param>
        /// <returns>密文</returns>
        public static string EncryptString(string strClearText)
        {
            return EncryptString(strClearText, "EsintKF2B@");
        }

        /// <summary>
        /// 加密指定字符串
        /// </summary>
        /// <param name="strClearText">明文</param>
        /// <param name="strKey">密钥</param>
        /// <returns>密文</returns>
        public static string EncryptString(string strClearText, string strKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            byte[] bytClearText;
            byte[] bytCipherText;
            bytClearText = Encoding.Default.GetBytes(strClearText);
            DES.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            DES.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            System.IO.MemoryStream MS = new System.IO.MemoryStream();
            CryptoStream CS = new CryptoStream(MS, DES.CreateEncryptor(), CryptoStreamMode.Write);
            CS.Write(bytClearText, 0, bytClearText.Length);
            CS.FlushFinalBlock();
            bytCipherText = MS.ToArray();
            CS.Close();
            MS.Close();
            return Convert.ToBase64String(bytCipherText);
        }

        /// <summary>
        /// MD5加密指定字符串
        /// </summary>
        /// <param name="strClearText">明文</param>
        /// <returns>密文</returns>
        public static string EncryptStringMD5(string strClearText)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytClearText = Encoding.UTF8.GetBytes(strClearText);
            byte[] bytCipherText = md5.ComputeHash(bytClearText);
            string strCipherText = "";
            for (int i = 0; i < bytCipherText.Length; i++)
                strCipherText += bytCipherText[i].ToString("X").PadLeft(2, '0');
            return strCipherText;
        }

        /// <summary>
        /// 加密指定文本文件
        /// </summary>
        /// <param name="strFilePath">要加密的文件路径</param>
        /// <param name="strOutPath">加密后的文件输出路径</param>
        public static void EncryptFile(string strFilePath, string strOutPath)
        {
            EncryptFile(strFilePath, strOutPath, "EsintKF2B@");
        }

        /// <summary>
        /// 加密指定文本文件
        /// </summary>
        /// <param name="strFilePath">要加密的文件路径</param>
        /// <param name="strOutPath">加密后的文件输出路径</param>
        /// <param name="strKey">密钥</param>
        public static void EncryptFile(string strFilePath, string strOutPath, string strKey)
        {
            if (!File.Exists(strFilePath))//如果存在
            {
                throw new FileNotFoundException("没有找到指定的文件！");
                //return;
            }

            FileInfo FI1 = new FileInfo(strFilePath);
            if (FI1.Extension.ToUpper() != ".TXT")
            {
                throw new Exception("只能加密扩展名为.TXT的文本文件！");
                //return;
            }

            FileInfo FI2 = new FileInfo(strOutPath);
            if (FI2.Extension.ToUpper() != ".TXT")
            {
                throw new Exception("输出文件必须是扩展名为.TXT的文本文件！");
                //return;
            }

            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.IV = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            DES.Key = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            //得到要加密文件的字节流
            FileStream FSin = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
            StreamReader SR = new StreamReader(FSin, Encoding.Default);
            string strClearText = SR.ReadToEnd();
            byte[] bytText = Encoding.Default.GetBytes(strClearText);
            FSin.Close();

            FileStream FSout = new FileStream(strOutPath, FileMode.Create, FileAccess.Write);
            CryptoStream CS = new CryptoStream(FSout, DES.CreateEncryptor(), CryptoStreamMode.Write);
            try
            {
                //加密得到的文件字节流
                CS.Write(bytText, 0, bytText.Length);
                CS.FlushFinalBlock();
            }
            catch (Exception Ex)
            {
                throw new ApplicationException(Ex.Message);
            }
            finally
            {
                try
                {
                    FSout.Close();
                    CS.Close();
                }
                catch
                {
                    ;
                }
            }

        }

        /// <summary>
        /// 解密指定字符串
        /// </summary>
        /// <param name="strCipherText">密文</param>
        /// <returns>明文</returns>
        public static string DecryptString(string strCipherText)
        {
            return DecryptString(strCipherText, "EsintKF2B@");
        }

        /// <summary>
        /// 解密指定字符串
        /// </summary>
        /// <param name="strCipherText">密文</param>
        /// <param name="strKey">密钥</param>
        /// <returns>明文</returns>
        public static string DecryptString(string strCipherText, string strKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            byte[] bytClearText;
            byte[] bytCipherText = Convert.FromBase64String(strCipherText);
            DES.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            DES.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            System.IO.MemoryStream MS = new System.IO.MemoryStream();
            CryptoStream CS = new CryptoStream(MS, DES.CreateDecryptor(), CryptoStreamMode.Write);
            CS.Write(bytCipherText, 0, bytCipherText.Length);
            CS.FlushFinalBlock();
            bytClearText = MS.ToArray();
            CS.Close();
            MS.Close();
            return Encoding.Default.GetString(bytClearText);
        }

        /// <summary>
        /// 解密指定文本文件
        /// </summary>
        /// <param name="strFilePath">要解密的文件路径</param>
        /// <param name="strOutPath">解密后的文件输出路径</param>
        public static void DecryptFile(string strFilePath, string strOutPath)
        {
            DecryptFile(strFilePath, strOutPath, "EsintKF2B@");
        }

        /// <summary>
        /// 解密指定文本文件
        /// </summary>
        /// <param name="strFilePath">要解密的文件路径</param>
        /// <param name="strOutPath">解密后的文件输出路径</param>
        /// <param name="strKey">密钥</param>
        public static void DecryptFile(string strFilePath, string strOutPath, string strKey)
        {
            if (!File.Exists(strFilePath))//如果存在
            {
                throw new FileNotFoundException("指定的解密文件没有找到");
                //return;
            }

            FileInfo FI1 = new FileInfo(strFilePath);
            if (FI1.Extension.ToUpper() != ".TXT")
            {
                throw new Exception("只能解密扩展名为.TXT的文本文件！");
                //return;
            }

            FileInfo FI2 = new FileInfo(strOutPath);
            if (FI2.Extension.ToUpper() != ".TXT")
            {
                throw new Exception("输出文件必须是扩展名为.TXT的文本文件！");
                //return;
            }

            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.IV = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            DES.Key = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "MD5").Substring(0, 8));
            FileInfo file = new FileInfo(strFilePath);
            byte[] bytText = new byte[file.Length];
            //得到要解密文件的字节流
            FileStream FSin = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
            //解密文件
            try
            {
                CryptoStream CS = new CryptoStream(FSin, DES.CreateDecryptor(), CryptoStreamMode.Read);
                CS.Read(bytText, 0, bytText.Length);
            }
            catch (Exception err)
            {
                throw new ApplicationException(err.Message);
            }
            finally
            {
                try
                {
                    FSin.Close();
                }
                catch { ;}
            }
            FileStream FSout = new FileStream(strOutPath, FileMode.Create, FileAccess.Write);
            FSout.Write(bytText, 0, bytText.Length);
            FSout.Close();

        }

    }
}
